#include "udpclient.h"
#include <QMessageBox>
#include <QHostAddress>

udpclient::udpclient(QWidget *parent,Qt::WindowFlags f)
    : QDialog(parent,f)
{
    setWindowTitle(tr("UDP Client"));
    ReceiveTextEdit = new QTextEdit(this);
    CloseBtn = new QPushButton(tr("CLOSE"),this);
    mainLayout = new QVBoxLayout(this);
    mainLayout->addWidget(ReceiveTextEdit);
    mainLayout->addWidget(CloseBtn);
    connect(CloseBtn,SIGNAL(clicked(bool)),this,SLOT(CloseBtnCliked()));
    port=5555;
    udpSocket = new QUdpSocket;
    connect(udpSocket,SIGNAL(readyRead()),this,SLOT(dataReceived()));
    bool result = udpSocket ->bind(port);
    if(!result)
    {
        QMessageBox::information(this,tr("error"),tr("udp socket create error"));
        return;
    }

}

udpclient::~udpclient()
{

}

void udpclient::CloseBtnCliked()
{
    close();
}

void udpclient::dataReceived()
{
    while(udpSocket->hasPendingDatagrams())
    {
        QByteArray datagram;
        datagram.resize(udpSocket->pendingDatagramSize()); //reset the array size for receive new data
        udpSocket->readDatagram(datagram.data(),datagram.size());
        QString msg = datagram.data();
        ReceiveTextEdit->insertPlainText(msg);
    }
}
